package com.kukudb.asaproject.serveice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kukudb.asaproject.pojo.CardKeys;
import com.kukudb.asaproject.pojo.UserLicenses;
import com.kukudb.asaproject.pojo.paramsDto.CreateCardKeysDto;
import com.kukudb.asaproject.pojo.paramsDto.UserCardKeyDto;
import com.kukudb.asaproject.pojo.resultDto.UseCardKeyDto;
import com.kukudb.asaproject.repository.CardKeysRepository;
import com.kukudb.asaproject.repository.UserLicensesRepository;
import com.kukudb.asaproject.serveice.interfaceTemp.CardKeysInterface;
import com.kukudb.asaproject.utils.DateUtils;
import com.kukudb.asaproject.utils.RandomUtils;
import org.apache.ibatis.executor.BatchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CardKeysImpl implements CardKeysInterface {
    Logger logger = LoggerFactory.getLogger(CardKeysImpl.class);
    @Autowired
    CardKeysRepository cardKeysRepository;

    @Autowired
    UserLicensesRepository userLicensesRepository;
    @Override
    public List<CardKeys> createCardKeys(CreateCardKeysDto createCardKeysDto) {
        List<CardKeys> cardKeysList = new ArrayList<>();
        //创建卡密
        if (createCardKeysDto.getQuantity() > 0 && createCardKeysDto.getQuantity() <= 10000) {
            for (int i = 0; i < createCardKeysDto.getQuantity(); i++) {
                //生成卡密
                String cardKey = RandomUtils.generateRandomCardKey(16);
                //保存卡密
                CardKeys cardKeys = new CardKeys();
                BeanUtils.copyProperties(createCardKeysDto, cardKeys);
                cardKeys.setCardKey(cardKey);
                cardKeys.setStatus("0");
                cardKeys.setCreateTime(new Date());
                cardKeys.setValue(createCardKeysDto.getValue());
                //过期时间设置为十天以后
//                cardKeys.setExpireTime(DateUtils.parseDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(new Date().toInstant().plusSeconds(864000))));
                cardKeysList.add(cardKeys);
            }
        }
        List<BatchResult> insert = cardKeysRepository.insert(cardKeysList);
        logger.info("创建卡密结束，返回结果为：" + insert.size());
        return cardKeysList;
    }

    @Override
    public List<CardKeys> getCardKeys(Integer userId) {
        logger.info("开始获取卡密列表，用户id为：" + userId);
        QueryWrapper<CardKeys> eq = new QueryWrapper<CardKeys>().eq("creator_id", userId);
        List<CardKeys> cardKeysList = cardKeysRepository.selectList(eq);
        return cardKeysList;
    }

    @Override
    public List<CardKeys> getAllCardKeys() {
        logger.info("开始获取所有卡密列表");
        List<CardKeys> cardKeysList = cardKeysRepository.selectList(null);
        return cardKeysList;
    }

    @Override
    public UseCardKeyDto useCardKeys(UserCardKeyDto userCardKeyDto, Integer userId) {
        logger.info("开始使用卡密，用户id为：" + userId);
        logger.info("卡密为：" + userCardKeyDto.getCardKey());
        //查询卡密

        QueryWrapper<CardKeys> eq = new QueryWrapper<CardKeys>().eq("card_key", userCardKeyDto.getCardKey());
        logger.info("查询卡密条件：" + eq);
        CardKeys cardKeys = cardKeysRepository.selectOne(eq);
        logger.info("查询卡密结果：" + cardKeys);
        if (cardKeys != null) {
            //判断卡密是否过期
            if (cardKeys.getExpireTime() != null && cardKeys.getExpireTime().before(new Date())) {
                logger.info("卡密已过期");
                throw new RuntimeException("卡密已过期");
            }
            //判断卡密是否被使用
            if ("1".equals(cardKeys.getStatus())) {
                logger.info("卡密已被使用");
                throw new RuntimeException("卡密已被使用");
            }else {
                //使用卡密状态
                //修改状态
                logger.info("卡密存在，使用卡密状态");

                //使用卡密，
                //操作userlicenses
                //查询现有用户的授权情况，获取授权类型，判断是否可以继续使用次数卡
                QueryWrapper<UserLicenses> queryWrapper = new QueryWrapper<UserLicenses>()
                       .eq("user_id", userId);
                UserLicenses userLicenses = userLicensesRepository.selectOne(queryWrapper);
                if (userLicenses != null) {
                    if ("2".equals(userLicenses.getLicenseType())) {
                        //次数卡
                        if ("1".equals(cardKeys.getKeyType())  ){
                            throw new RuntimeException("次数卡授权用户暂时不能使用其他卡密");
                        }
//                        userLicensesRepository.updateById(userLicenses);
                    }else if ("1".equals(userLicenses.getLicenseType())){
                        if ("2".equals(cardKeys.getKeyType()) ){
                            cardKeys.setValue(0);
//                            throw new RuntimeException("时长卡用户暂时不能使用次数卡");
                        }
                        userLicenses.setEndTime(DateUtils.addDays(userLicenses.getEndTime(), cardKeys.getValue()));
                    }
                    userLicenses.setTotalValue(userLicenses.getTotalValue() + cardKeys.getValue());
                    userLicenses.setUpdateTime(new Date());
                    userLicensesRepository.updateById(userLicenses);
                }else {
                    //没有授权，则创建授权
                    logger.info("没有授权，则创建授权");
                    userLicenses = new UserLicenses();
                    userLicenses.setUserId(userId);
                    userLicenses.setKeyId(cardKeys.getKeyId());
                    userLicenses.setLicenseType(cardKeys.getKeyType());
                    userLicenses.setTotalValue(cardKeys.getValue());
                    userLicenses.setUsedValue(0);
                    userLicenses.setStartTime(new Date());
                    if ("1".equals(cardKeys.getKeyType())) {
                        Date date = DateUtils.addDays(new Date(), cardKeys.getValue());
                        userLicenses.setEndTime(date);
//                        userLicenses.setEndTime(DateUtils.parseDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(new Date().toInstant().plusSeconds(cardKeys.getValue() * 86400))));
                }
                    userLicenses.setStatus("1");
                    userLicenses.setCreateTime(new Date());
                    userLicenses.setUpdateTime(new Date());
                    logger.info("创建授权：" + userLicenses.toString());
                    userLicensesRepository.insert(userLicenses);
                }
                UseCardKeyDto useCardKeyDto = new UseCardKeyDto();
                BeanUtils.copyProperties(cardKeys, useCardKeyDto);
                BeanUtils.copyProperties(userLicenses, useCardKeyDto);
                logger.info("使用卡密结束，返回结果为：" + useCardKeyDto.toString());
                cardKeys.setStatus("1");
                cardKeysRepository.updateById(cardKeys);
                return useCardKeyDto;
            }
        }
        throw new RuntimeException("卡密不存在");
    }

    @Override
    public void deleteCardKeys(Integer userId) {
        logger.info("开始删除卡密，用户id为：" + userId);
        QueryWrapper<CardKeys> eq = new QueryWrapper<CardKeys>().eq("creator_id", userId);
        List<CardKeys> cardKeysList = cardKeysRepository.selectList(eq);
        for (CardKeys cardKeys : cardKeysList) {
            cardKeysRepository.deleteById(cardKeys.getKeyId());
        }
        logger.info("删除卡密结束");
        return;
    }

    @Override
    public void deleteAllCardKeys() {
        logger.info("开始删除所有卡密");
        cardKeysRepository.delete(null);
        logger.info("删除所有卡密结束");
        return;
    }

    @Override
    public void addUsedCont(Integer userId, int i) {
        logger.info("开始增加已用次数，用户id为：" + userId);
        QueryWrapper<UserLicenses> queryWrapper = new QueryWrapper<UserLicenses>()
               .eq("user_id", userId);
        UserLicenses userLicenses = userLicensesRepository.selectOne(queryWrapper);
        if (userLicenses != null) {
            userLicenses.setUsedValue(userLicenses.getUsedValue() + i);
            userLicenses.setUpdateTime(new Date());
            userLicensesRepository.updateById(userLicenses);
        }
        logger.info("增加已用次数结束");
        return;
    }
}
